<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-sRIl4kxILFvY47J16cr9ZwB07vP4J8+LH7qKQnuqkuIAvNWLzeN8tE5YBujZqJLB" crossorigin="anonymous">
  <style>
    .pagination {
      justify-content: flex-end;
    }
    .search {
      margin: 20px 0;
      display: flex;
    }
    .search-input {
      width: 300px;
      margin-right: 30px;
    }
  </style>
</head>
<body>
  <div class="container">
    <h1>学生管理系统</h1>

    <!-- 搜索功能 -->
    <div class="search">
      <input type="text" class="form-control search-input" placeholder="请输入姓名">
      <button type="button" class="btn btn-primary search-button">搜索</button>
      <button type="button" class="btn btn-primary reset-button">重置</button>
    </div>

    <!-- 新增 -->
    <div class="add">
      <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addModal">
        新增
      </button>
    </div>

    <table class="table">
      <thead>
        <tr>
          <th scope="col">姓名</th>
          <th scope="col">年龄</th>
          <th scope="col">性别</th>
          <th scope="col">学号</th>
          <th scope="col">爱好</th>
          <th scope="col">操作</th>
        </tr>
      </thead>
      <tbody>
        
      </tbody>
    </table>

    <nav aria-label="Page navigation example">
      <ul class="pagination">
      </ul>
    </nav>



    <!-- 删除按钮点击以后的二次确认框 -->
    <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h1 class="modal-title fs-5" id="exampleModalLabel">删除</h1>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            你确定要删除吗?
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            <button type="button" class="btn btn-primary" onclick="confirm()">确定</button>
          </div>
        </div>
      </div>
    </div>

    <!-- 新增时的弹出框 -->
    <div class="modal fade" id="addModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h1 class="modal-title fs-5" id="exampleModalLabel">新增学员</h1>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            <div class="mb-3">
              <label for="exampleFormControlInput1" class="form-label">姓名</label>
              <input type="text" class="form-control" id="exampleFormControlInput1" placeholder="请输入姓名">
            </div>
            <div class="mb-3">
              <label for="exampleFormControlInput2" class="form-label">年龄</label>
              <input type="number" class="form-control" id="exampleFormControlInput2" placeholder="请输入年龄">
            </div>
            <div class="mb-3">
              <label for="exampleFormControlInput3" class="form-label">性别</label>
              <select class="form-select" aria-label="Default select example" id="exampleFormControlInput3">
                <option selected disabled>-- 请选择区别 --</option>
                <option value="1">男</option>
                <option value="2">女</option>
              </select>
            </div>
            <div class="mb-3">
              <label for="exampleFormControlInput4" class="form-label">学号</label>
              <input type="number" class="form-control" id="exampleFormControlInput4" placeholder="请输入学号">
            </div>
            <div class="mb-3">
              <label for="exampleFormControlInput5" class="form-label">爱好</label>
              <input type="text" class="form-control" id="exampleFormControlInput5" placeholder="请输入爱好, 如果有多个, 用逗号隔开">
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
            <button type="button" class="btn btn-primary" onclick="confirmAdd()">确定</button>
          </div>
        </div>
      </div>
    </div>
  </div>
  


  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/js/bootstrap.bundle.min.js" integrity="sha384-FKyoEForCGlyvwx9Hj09JcYn3nv7wiPVlz7YYwJrWVcXK/BmnVDxM+D2scQbITxI" crossorigin="anonymous"></script>

  <script src="./request.js"></script>
  <script>
    let pageSize = 3;
    let pageNum = 1;
    let searchValue = "";
    let removeId = "";
    let dataList = [];

    // 数据请求
    function getData() {
      request.get("/index/list", {
        pageSize,
        pageNum,
        searchValue
      }).then(res => {
        if (res.success) {
          // 对res.data做循环，并且添加到tbody的里面
          dataList = res.data;
          let str = "";
          dataList.forEach(item => {
            str += `
              <tr>
                <td>${item.name}</td>
                <td>${item.age}</td>
                <td>${item.sex === 1 ? "男" : "女"}</td>
                <td>${item.num}</td>
                <td>${item.likes}</td>
                <td>
                  <button type="button" class="btn btn-warning btn-sm" onclick="edit('${item._id}')">编辑</button>  
                  <button type="button" class="btn btn-danger btn-sm" data-bs-toggle="modal" data-bs-target="#exampleModal" onclick="remove('${item._id}')">删除</button>
                </td>
              </tr>
            `
          })
          document.querySelector("tbody").innerHTML = str;


          // 还需要对分页器做操作
          let str2 = '<li class="page-item"><a class="page-link" href="#">Previous</a></li>';
          let page = Math.ceil(res.count / pageSize);
          for (let i = 1; i <= page; i++) {
            // 可以在标签里面添加点击事件，并且传参
            str2 += `<li class="page-item" onclick="fn(${i})"><a class="page-link" href="#">${i}</a></li>`
          }
          str2 += `<li class="page-item"><a class="page-link" href="#">Next</a></li>`
          document.querySelector(".pagination").innerHTML = str2;
        } else {
          location.href = "./login.html"
        }
      })
      // fetch(`http://127.0.0.1:3000/api/index/list?pageSize=${pageSize}&pageNum=${pageNum}&searchValue=${searchValue}`, {
      //   headers: {
      //     // 前端推荐在请求头里面传递token
      //     token: localStorage.getItem("token")
      //   }
      // })
      //   .then(response => response.json())
      //   .then(res => {
      //     if (res.success) {
      //       // 对res.data做循环，并且添加到tbody的里面
      //       dataList = res.data;
      //       let str = "";
      //       dataList.forEach(item => {
      //         str += `
      //           <tr>
      //             <td>${item.name}</td>
      //             <td>${item.age}</td>
      //             <td>${item.sex === 1 ? "男" : "女"}</td>
      //             <td>${item.num}</td>
      //             <td>${item.likes}</td>
      //             <td>
      //               <button type="button" class="btn btn-warning btn-sm" onclick="edit('${item._id}')">编辑</button>  
      //               <button type="button" class="btn btn-danger btn-sm" data-bs-toggle="modal" data-bs-target="#exampleModal" onclick="remove('${item._id}')">删除</button>
      //             </td>
      //           </tr>
      //         `
      //       })
      //       document.querySelector("tbody").innerHTML = str;


      //       // 还需要对分页器做操作
      //       let str2 = '<li class="page-item"><a class="page-link" href="#">Previous</a></li>';
      //       let page = Math.ceil(res.count / pageSize);
      //       for (let i = 1; i <= page; i++) {
      //         // 可以在标签里面添加点击事件，并且传参
      //         str2 += `<li class="page-item" onclick="fn(${i})"><a class="page-link" href="#">${i}</a></li>`
      //       }
      //       str2 += `<li class="page-item"><a class="page-link" href="#">Next</a></li>`
      //       document.querySelector(".pagination").innerHTML = str2;
      //     } else {
      //       location.href = "./login.html"
      //     }
      //   })
    }
    
    getData();

    // 分页
    function fn(i) {
      // 点击页码触发的函数
      console.log(i);
      pageNum = i;
      getData();
    }


    // 搜索
    document.querySelector(".search-button").onclick = () => {
      searchValue = document.querySelector(".search-input").value;
      pageNum = 1;
      getData();
    }

    // 重置
    document.querySelector(".reset-button").onclick = () => {
      searchValue = "";
      document.querySelector(".search-input").value = "";
      getData();
    }
  
    // 点击删除按钮
    function remove(id) {
      removeId = id;
    }
    // 确定删除
    function confirm () {
      // console.log(removeId);
      // 拿到id之后，需要请求接口了
      request.post("/index/del", {removeId}).then(res => {
        if (res.success) {
          // 模态框隐藏掉
          bootstrap.Modal.getOrCreateInstance(document.getElementById('exampleModal')).hide()
          // 更新数据
          getData();
        }
      })
      // fetch("http://127.0.0.1:3000/api/index/del", {
      //   method: "POST",
      //   body: JSON.stringify({removeId}),
      //   headers: {"content-type": "application/json"}
      // }).then(response => response.json())
      // .then(res => {
      //   if (res.success) {
      //     // 模态框隐藏掉
      //     bootstrap.Modal.getOrCreateInstance(document.getElementById('exampleModal')).hide()
      //     // 更新数据
      //     getData();
      //   }
      // })
    }
  
  
    // 确定新增
    function confirmAdd() {
      request.post("/index/add", {
        name: document.querySelector("#exampleFormControlInput1").value,
        age: document.querySelector("#exampleFormControlInput2").value,
        sex: document.querySelector("#exampleFormControlInput3").value,
        num: document.querySelector("#exampleFormControlInput4").value,
        likes: document.querySelector("#exampleFormControlInput5").value,
      }).then(res => {
        bootstrap.Modal.getOrCreateInstance(document.getElementById('addModal')).hide();
        getData();
      })

      // fetch("http://127.0.0.1:3000/api/index/add", {
      //   method: "POST",
      //   body: JSON.stringify({
      //     name: document.querySelector("#exampleFormControlInput1").value,
      //     age: document.querySelector("#exampleFormControlInput2").value,
      //     sex: document.querySelector("#exampleFormControlInput3").value,
      //     num: document.querySelector("#exampleFormControlInput4").value,
      //     likes: document.querySelector("#exampleFormControlInput5").value,
      //   }),
      //   headers: {"content-type": "application/json"}
      // }).then(response => response.json())
      // .then(res => {
      //   if (res.success) {
      //     bootstrap.Modal.getOrCreateInstance(document.getElementById('addModal')).hide();
      //     getData();
      //   }
      // })
    }

    function edit(id) {
      // 通过这个id在dataList数组里面找出对应的那条数据
      const result = dataList.find(item => {
        return item._id === id
      })
      console.log(result);
      
    }
  </script>
</body>
</html>